package com.yh.csx.etl.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 文件工具类
 * 
 * @author Robin.Wang
 * @date 2020-03-20
 */
public class FileUtils {
    private static final Logger log = LoggerFactory.getLogger(FileUtils.class);

    /**
     * 获取配置文件路径
     */
    public static File getConfDirPath() {
        return getConfDirPath("");
    }

    /**
     * 获取配置文件路径
     */
    public static File getConfDirPath(String subConf) {
        URL url = FileUtils.class.getClassLoader().getResource("");
        String path;
        if (url != null) {
            path = url.getPath();
        } else {
            path = new File("").getAbsolutePath();
        }
        File file = null;
        if (path != null) {
            file = new File(path + ".." + File.separator + ConstantUtils.CONF_DIR + File.separator
                    + StringUtils.trimToEmpty(subConf));
            if (!file.exists()) {
                file = new File(path + StringUtils.trimToEmpty(subConf));
            }
        }
        if (file == null || !file.exists()) {
            throw new RuntimeException("Config dir not found.");
        }

        return file;
    }

    /**
     * 读取文件
     * 
     * @throws IOException
     */
    public static String readFile(String path) {
        StringBuilder sb = new StringBuilder();
        File file = new File(path);
        if (file.exists()) {
            try (FileReader reader = new FileReader(file); BufferedReader bufr = new BufferedReader(reader);) {
                String line = null;
                while ((line = bufr.readLine()) != null) {
                    sb.append(line).append("\n");
                }
            } catch (FileNotFoundException e) {
                log.error("File not found", e);
            } catch (IOException e) {
                log.error("File Read Exception", e);
            }

        }
        return sb.toString();
    }
}
